<script setup lang="ts">
import type { PropType } from 'vue'
import { computed } from 'vue'
import { IconCheckCircleFill, IconExclamationCircleFill } from '@arco-design/web-vue/es/icon'
import { isArray, isUndefined } from '@/utils/typed'

defineOptions({ name: 'ValidateSelect' })

const $props = defineProps({
  modelValue: {
    type: [String, Number, Boolean, Object, Array] as PropType<
        SelectModelValue | SelectModelValue[]
    >,
    default: undefined,
  },
  validator: {
    type: Function as PropType<() => boolean>,
    default: undefined,
  },
})

const $emits = defineEmits(['update:modelValue', 'input', 'change'])

  type SelectModelValue = string | number | boolean | Record<string, any>

const computedValue = computed<
  | string
  | number
  | boolean
  | Record<string, any>
  | (string | number | boolean | Record<string, any>)[]
  | undefined
>({
      get: () => $props.modelValue,
      set: (newValue) => {
        $emits('update:modelValue', newValue)
        $emits('input', newValue)
        $emits('change', newValue)
      },
    })

const computedValidateState = computed<boolean>(() => {
  if ($props.validator && typeof $props.validator === 'function') {
    return $props.validator()
  }
  if (typeof $props.modelValue === 'string' || isArray($props.modelValue)) {
    return !!$props.modelValue.length
  }
  return !isUndefined(computedValue.value)
})
</script>

<template>
  <a-select v-model="computedValue" v-bind="$attrs" class="a-validate-select">
    <slot />
    <template #prefix>
      <div
        class="a-validate-select__suffix"
        :class="computedValidateState ? 'feedback-success' : 'feedback-error'"
      >
        <IconCheckCircleFill v-if="computedValidateState" size="16" />
        <IconExclamationCircleFill v-else size="16" />
      </div>
    </template>
  </a-select>
</template>

<style lang="scss">
  .a-validate-select {
    position: relative;
    /*隐藏原有前缀的内容*/
    &.arco-select-view-single {
      .arco-select-view-prefix {
        padding-right: 0;
      }
    }
    &.arco-select-view-multiple {
      .arco-select-view-prefix {
        padding-right: 0;
      }
    }

    .a-validate-select__suffix {
      position: absolute;
      width: 32px;
      height: 100%;
      top: 0;
      right: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 10;
      pointer-events: none;
      &.feedback-success .arco-icon {
        color: rgb(var(--success-6));
      }
      &.feedback-error .arco-icon {
        color: rgb(var(--warning-6));
      }
    }
  }
</style>
